import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';

import find from 'lodash/find';
import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, DescriptionItem } from '@/utils/utils';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import AddOrEditpermissions from './AddOrEdit';
import RolesDetail from './../Roles/AddOrEdit';
import ValidForm from './SetValidTime';
import ReactDataGrid from 'react-data-grid';
import AddOrEditRoles from '../Roles/AddOrEdit';

const FormItem = Form.Item;
const { confirm } = Modal;
const {Option} =Select
const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ permissions, loading, global }) => ({
  permissions,
  global,
  loading: loading.models.permissions,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      permissions: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        permissions: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'permissions/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'permissions/changeLoaded',
          });
          dispatch({
            type: 'permissions/changeTableY',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'permissions/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'permissions/changeTableY',
    });
  };
  findChildFunc = (cb) => {
    this.file = cb;
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    const table = document.querySelector('.react-grid-Canvas');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'permissions/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      permissions: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem label="分组">
          {getFieldDecorator('group', {
            initialValue: searchParams.group,
          })(
            <Select style={{width:'120px'}} allowClear={true}>
              {
                [{name:'集中器管理'},{name:'账号角色'}].map((item,index)=>{
                  return <Option key={index} value={item.name}>{item.name}</Option>
                })
              }
            </Select>
          )}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
            <Button
              icon="plus"
              style={{ marginLeft: 8 }}
              type="primary"
              onClick={
                () => {
                  this.setState({
                    addModal: true,
                  });
                }
              }
            >
              添加权限
            </Button>

        </FormItem>

      </Form>
    );
  }

  keyPress = (e) => {
    let theEvent = e || window.event;
    let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code === 13) {
      e.preventDefault();
      console.log('key press');
      const {
        permissions: { searchParams },
      } = this.props;
      const { form } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;

        this.handleSearch({
          page: 1,
          per_page: searchParams.per_page,
          ...fieldsValue,
        });

      });
    }
  };
  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'permissions/add',
      payload: {
        ...formValues,
      },
      callback() {
        message.success('添加权限成功');
        that.setState({
          addModal: false,
        });
        const {
          permissions: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      group: '',
      page: 1,
      per_page: 30,
    });
  };

  handleEdit = () => {
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: `permissions/edit`,
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
      },
      callback() {
        message.success('修改账号成功');
        that.setState({
          editModal: false,
        });
        const {
          permissions: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleEditValid = () => {
    const formValues = this.ValidForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: `permissions/editValid`,
      payload: {
        ...formValues,
        valid_time: formValues.valid_time ?
          moment(formValues.valid_time).format('YYYY-MM-DD HH:mm:ss') : '',
        id: this.state.editRecord.id,
      },
      callback() {
        message.success('有效期成功');
        that.setState({
          validModal: false,
        });
        const {
          permissions: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `permissions/remove`,
      payload: { id },
      callback: () => {
        message.success('删除账号成功');
        const {
          permissions: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleStatus = (id, status) => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `permissions/changeStatus`,
      payload: { id, status },
      callback: () => {
        message.success('修改账号状态成功');
        const {
          permissions: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleReset = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `permissions/resetPassword`,
      payload: { id },
      callback: () => {
        message.success('重置密码成功');
        // const {
        //   permissions: { searchParams },
        // } = that.props;
        // that.handleSearch(searchParams);
      },
    });
  };
  renderObserve = (val) => {
    let type = '';
    let color = '';
    let text = '';
    switch (val) {
      case -1:
        type = 'close-circle', color = '#eb2f96', text = '禁用';
        break;
      case 1:
        type = 'check-circle', color = '#52c41a', text = '启用';
        break;
      default:
        break;
    }
    return <Fragment> <Icon type={type} theme="twoTone" className="table-icon" twoToneColor={color}/>{text}</Fragment>;
  };

  render() {
    const that = this;
    const {
      permissions: { data, loading, tableY, meta, searchParams, selectedRowKeys },
      global: { gridTableW },
    } = this.props;
    const username = sessionStorage.getItem('username');
    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {
            permissions: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },

      {
        name: '名称',
        width: 150,
        key: 'name',
      },
      {
        name: '分组',
        width: 150,
        key: 'group',
      },
      {
        name: '操作',
        width: 200,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          <Button
            type="primary"
            size="small"
            icon="edit"
            onClick={(e) => {
              this.setState({
                editRecord: event.row,
                editModal: true,
              });
            }
            }
          >编辑
          </Button>
          <Button
            type="danger"
            size="small"
            icon="delete"
            onClick={(e) => {
              confirm({
                title: `确定要删除"${event.row.name}"吗?`,
                content: '请谨慎操作！',
                okText: '确定',
                okType: 'danger',
                cancelText: '取消',
                centered: true,
                maskClosable: true,
                onOk() {
                  that.handleDelete(event.row.id);
                },
                onCancel() {
                  console.log('Cancel');
                },
              });
            }
            }
          >删除
          </Button>

        </Fragment>,
      },
    ].map(c => ({ ...defaultColumnProperties, ...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>权限管理</span>
      </div>
      <div className="table-page">
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            rowsCount={data.length}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (row) => {
                this.props.dispatch({
                  type: 'permissions/changeSelectRow',
                  payload: [row],
                });
              }
            }

          />
          {
            loading && <Loading/>
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }} meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.addModal} modalClass="addModal" title="添加权限"/>}
        visible={this.state.addModal}
        centered
        onOk={this.handleAdd}
        className="addModal"
        onCancel={() => {
          this.setState({ addModal: false });
        }}

      >
        <AddOrEditpermissions wrappedComponentRef={(inst) => this.AddForm = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                title={`修改 : ${this.state.editRecord.username}`}/>}
        destroyOnClose
        visible={this.state.editModal}
        centered
        onOk={this.handleEdit}
        className="editModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ editModal: false, editRecord: {} });
        }}

      >
        <AddOrEditpermissions
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.EditForm = inst}
        />

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.validModal} modalClass="validModal"
                                title={`${this.state.editRecord.username} 有效期设置`}/>}
        destroyOnClose
        visible={this.state.validModal}
        centered
        onOk={this.handleEditValid}
        className="validModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ validModal: false, editRecord: {} });
        }}

      >
        <ValidForm
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.ValidForm = inst}
        />

      </Modal>
      <Drawer
        title={`${this.state.editRecord.role_name} 详情`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            roleModal: false,
            editRecord: {},
          });
        }}
        width={700}
        visible={this.state.roleModal}
      >
        <AddOrEditRoles
          hiddenSave={true}
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.EditForm = inst}
        />
      </Drawer>

    </div>;
  }
}

export default BasicList;
